document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('participant-form').addEventListener('submit', function(event) {
        event.preventDefault();
        var participantName = document.getElementById('participant-name').value;
        fetch('/participant', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({name: participantName}),
        })
            .then(response => response.json())
            .then(data => {
            console.log(data);
            document.getElementById('participant-name').value = '';
        })
            .catch((error) => {
            console.error('Error:', error);
        });
    });

    document.getElementById('draw-button').addEventListener('click', function() {
        var items = document.getElementsByClassName('grid-item');
        var index = 0;
        var interval = setInterval(function() {
            items[index].classList.remove('active');
            index = (index + 1) % items.length;
            items[index].classList.add('active');
        }, 100);
        setTimeout(function() {
            clearInterval(interval);
            var prize = items[index].getAttribute('data-prize');
            fetch('/draw', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({prize: prize}),
            })
                .then(response => response.json())
                .then(data => {
                console.log(data);
                if (data.code !== 1) {
                    alert(data.message);
                } else {
                    var li = document.createElement("li");
                    li.appendChild(document.createTextNode(data.message));
                    document.getElementById('prize-list').appendChild(li);
                }
            })
                .catch((error) => {
                console.error('Error:', error);
            });
        }, Math.floor(Math.random() * (10000 - 3000 + 1)) + 3000);
    });
});

